package com.hengyu.oauth2.core;

import com.hengyu.oauth2.entity.HengYuOAuth2UserDetails;
import com.hengyu.oauth2.jpa.HengYuUserDetailsJPA;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.List;

/**
 * 自定义oauth用户查询业务逻辑
 * 项目名称：OAuth2Example
 * 项目版本：V1.0
 * 包名称：com.example.oauth
 * 创建人：yuqy
 * 创建时间：2017/3/16 18:33
 * 修改人：yuqy
 * 修改时间：2017/3/16 18:33
 * 修改备注：
 */
@Service
public class HengYuOAuth2UserDetailsService implements UserDetailsService
{
    //注入用户查询SpringDataJpa数据接口
    @Autowired
    private HengYuUserDetailsJPA userDetailsDAO;

    /**
     * 实现接口方法，oauth自动调用该实现方法来验证oauth/token获取时的用户查询情况
     * @param userName 用户名
     * @return 用户详情 HengYuOAuth2UserDetails 实现了UserDetails接口
     * @throws UsernameNotFoundException 抛出异常
     */
    @Override
    public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
        //查询是否存在该用户信息
        List<HengYuOAuth2UserDetails> users = userDetailsDAO.findAll(new Specification<HengYuOAuth2UserDetails>() {
            @Override
            public Predicate toPredicate(Root<HengYuOAuth2UserDetails> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
                criteriaQuery.where(criteriaBuilder.equal(root.get("userName"),userName));
                return null;
            }
        });
        //size == 0
        if(users == null || users.size() == 0)
        {
            throw new UsernameNotFoundException("not found user of " + userName);
        }
        //size > 1
        if(users.size() > 1)
        {
            throw new UsernameNotFoundException("Found "+users.size()+" Users of "+userName);
        }
        //return user info
        return users.get(0);
    }
}
